package icom.acm.action.mircblog;

import icom.acm.action.Action;
import icom.acm.bean.T_USER;
import icom.acm.bean.VIEW_USER_RELATION_ONLINE;
import icom.acm.bean.mircblog.T_MB_MESSAGE;
import icom.acm.bean.mircblog.VIEW_USER_MBMESSAGE;
import icom.acm.form.mircblog.MessageForm;
import icom.acm.manager.View_User_Relation_OnlineMgr;
import icom.acm.manager.mircblog.T_MB_MessageMgr;
import icom.acm.manager.mircblog.View_User_MBMessageMgr;
import icom.acm.manager.mircblog_mongo.View_User_MBMessageMongoMgr;
import icom.acm.util.DBConnect;
import icom.acm.util.RedisUtil;
import icom.acm.util.json.JSONMsg;
import icom.acm.util.mongo.MongoDB;
import icom.acm.util.redis.RedisDB;

import java.io.UnsupportedEncodingException;
import java.util.List;

import redis.clients.jedis.Jedis;

import com.mongodb.DBObject;

public class MessageAction extends Action{
	/**
	 * 以下变量需要有get set方法，这样html中传入的参数就可以自动得到
	 * 如果是基本类型int，String。。。的变量 html中形式：http://..../xx?a=?
	 * 如果是自定义变了则: http://..../xx?u.id=?&u.xx=?
	 */
	private T_MB_MESSAGE msg;
	private String token;
	private MessageForm form;
	
	public String forget(){
		toUrl = "forget.jsp";
		
		return "TOURL";
	}
	
	public void test(){
		System.out.println("test");
		response.setCharacterEncoding("utf-8");
		JSONMsg jsonmsg = new JSONMsg(Boolean.TRUE, "gfsf");
		out.print(jsonmsg.toString());		
	}
	
	public void postMsg() {
		JSONMsg jmsg = null;
		T_USER user = checkUser();
		if (user==null) {
			jmsg = new JSONMsg(false, "用户未登录!");
			out.print(jmsg.toString());
			return ;
		}
		// 防止重复提交
		String token = (String)session.getAttribute("token");
		if (token==null){
			jmsg = new JSONMsg(false, "重复提交!");
			out.print(jmsg.toString());
			return ;
		} else if (!token.equals(this.token)){
			jmsg = new JSONMsg(false, "已提交!");
			out.print(jmsg.toString());
			return ;
		}	
		session.removeAttribute("token");
		try {
			msg.setM_CONTENT(new String(msg.getM_CONTENT().getBytes("ISO-8859-1"),"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		T_MB_MessageMgr mmgr = new T_MB_MessageMgr();		
		View_User_Relation_OnlineMgr vuromgr = new View_User_Relation_OnlineMgr();		
		View_User_MBMessageMongoMgr mmgmgr = new View_User_MBMessageMongoMgr();
		View_User_MBMessageMgr vummmgr = new View_User_MBMessageMgr();
		DBConnect db = new DBConnect();
		Jedis jedis = RedisDB.newInstance().get_Jedis();
		String ids = "";
		try {
			msg.setM_U_ID(user.getU_ID());
			msg = mmgr.insert(msg, db);		// 存入数据库
			VIEW_USER_MBMESSAGE vumm = vummmgr.selectByMid(msg.getM_ID(), db);
			List<VIEW_USER_RELATION_ONLINE> list = vuromgr.selectByUedId(msg.getM_U_ID(), db);	// 得到用户的关注者
			//MsgCache.put(user, msg); 
			mmgmgr.insert(vumm); 			// 插入在mongo数据库中保存
			for (int i=0;i<list.size() ;i++){// 插入到redis数据队列中
				Integer id = list.get(i).getVURO_U_ID();
				String sessionid = list.get(i).getVURO_SESSIONID();
				
				if (i>0) ids = ids + ",";
				ids = ids + sessionid;
				
				String key = RedisUtil.KEY_MESSAGE2USER+id;
				jedis.expire(key, RedisUtil.KEY_MESSAGE2USER_EXPIRE);
				jedis.rpush(key , String.valueOf(msg.getM_ID()));
			}
			jmsg = new JSONMsg(true, ids);
			jmsg.include(vumm.toJson());
		} catch (Exception ex){
			jmsg = new JSONMsg(false, "未知的错误!");			
			ex.printStackTrace();
		} finally{
			if (msg!=null){
				out.print(jmsg);
			}
			RedisDB.newInstance().close(jedis);
			db.close();
		}		
	}
	
	public void recive(){
		JSONMsg jmsg = null;
		T_USER user = checkUser();
		if (user==null) {
			jmsg = new JSONMsg(false, "用户未登录!");
			out.print(jmsg.toString());
			return ;
		}
		int id = user.getU_ID().intValue();				
		View_User_MBMessageMongoMgr mmgmgr = new View_User_MBMessageMongoMgr();
		Jedis jedis = RedisDB.newInstance().get_Jedis();
		MongoDB dbmongo = MongoDB.newInstance();
		String key = RedisUtil.KEY_MESSAGE2USER + id;
		String json = "";				
		//List<String> msgids = dbredis.lrange(key, 0 , -1);
		boolean flag = false;
		while (true){
			String msgid = jedis.rpop(key);
			if (msgid==null || msgid.equals("")){
				break;
			}
			DBObject o = mmgmgr.findByMid(msgid, dbmongo);
			if (flag) json = json + ",";
			else flag = true;
			json = json + o.toString();
		}		
				
		RedisDB.newInstance().close(jedis);
		jmsg = new JSONMsg(true, "成功发送json");
		jmsg.include(json);
		out.print(jmsg.toString());
	}

	public void list(){
		T_USER user = checkUser();
		if (user==null) return ;
		T_MB_MessageMgr msgMgr = new T_MB_MessageMgr();
		List<T_MB_MESSAGE> list = msgMgr.selectByUidOrFriend(user.getU_ID());
	}
	
	public String DelMsg(){
		// 防止重复提交
		String token = (String)session.getAttribute("token");
		if (token==null){
			return "ERROR";
		} else if (!token.equals(this.token)){
			return "ERROR";
		}
		session.removeAttribute("token");
		
		T_MB_MessageMgr msgMgr = new T_MB_MessageMgr();
		if (!msgMgr.Delete(msg.getM_ID())){
			return "ERROR";
		}
		else
		{
			return "SUCCESS";
		}				
	}
	
	public void showMessages(){
		JSONMsg jmsg = null;
		T_USER user = checkUser();
		if (user==null) {
			jmsg = new JSONMsg(false, "用户未登录!");
			out.print(jmsg.toString());
			return ;
		}
		
		View_User_MBMessageMgr vummm = new View_User_MBMessageMgr();
		DBConnect db = new DBConnect();
		try {
			List<VIEW_USER_MBMESSAGE> list = vummm.selectsOBDate(db, user.getU_ID(), form.getStart(), form.getPagesize());
			jmsg = new JSONMsg(true, "成功");
			String json = "";
			for (int i=0;i<list.size();i++){
				VIEW_USER_MBMESSAGE e = list.get(i);
				if (i>0) json = json + ",";
				json = json + e.toJson();
			}			
			jmsg.include(json);			
		} catch (Exception e) {
			jmsg = new JSONMsg(false, "未知的错误!"+e.getMessage());
			e.printStackTrace();
		} finally {
			if (jmsg != null)
				out.print(jmsg.toString());
			db.close();
		}
	}

	public T_MB_MESSAGE getMsg() {
		return msg;
	}

	public void setMsg(T_MB_MESSAGE msg) {
		this.msg = msg;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public MessageForm getForm() {
		return form;
	}

	public void setForm(MessageForm form) {
		this.form = form;
	}
}
